from rest_framework.views import  APIView
from rest_framework import response, status
from . import serializers
from .models import Reagent

class ReagentList(APIView):
    def get(self, request):
        # 获取查询参数
        name = request.query_params.get('name','').strip()
        supplier = request.query_params.get('supplier','').strip()
        location = request.query_params.get('location','').strip()
        safety_level = request.query_params.get('safety_level','').strip()

        queryset = Reagent.objects.all()

        if name:
            queryset = queryset.filter(name__icontains=name)
        if supplier:
            queryset = queryset.filter(supplier__icontains=supplier)
        if location:
            queryset = queryset.filter(location__icontains=location)
        if safety_level:
            queryset = queryset.filter(safety_level=safety_level)

        # 分页参数
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('pageSize', 10))
        start = (page - 1) * page_size
        end = start + page_size

        serializer = serializers.ReagentSerializer(queryset[start:end], many=True)
        # print(serializer.data)
        return response.Response({
            'data': serializer.data,
            'total': queryset.count(),
            'page': page,
            'pageSize': page_size,
        })
    def post(self, request):
        serializer = serializers.ReagentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return response.Response(serializer.data, status=status.HTTP_201_CREATED)
        return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class ReagentDetail(APIView):
    def put(self, request, pk):
        reagent = Reagent.objects.get(pk=pk)
        serializer = serializers.ReagentSerializer(reagent, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return response.Response(serializer.data)
        return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    def delete(self, request, pk):
        reagent = Reagent.objects.get(pk=pk)
        reagent.delete()
        return response.Response(status=status.HTTP_204_NO_CONTENT)

